﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using System.Linq;

namespace MoutasemA.ManageMappedPages.ControlTemplates.MoutasemA.ManageMappedPages
{
    public partial class ManageMappedPagesUC : UserControl
    {
        const string FILE_NOT_FOUND_404 = "404 - File Not found page";
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                lblError.Text = "";
                if (!IsPostBack)
                {
                    loadPageTypes();
                }
            }
            catch (Exception ex)
            {
                logError(ex);

            }
        }

        private void loadPageTypes()
        {
            var pageTypes = Enum.GetNames(typeof(SPWebApplication.SPCustomPage)).ToList();
            pageTypes.Add(FILE_NOT_FOUND_404);
            ddlPageType.DataSource = pageTypes;
            ddlPageType.DataBind();
        }

        protected void ddlPageType_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                loadPageTypeUrl();
            }
            catch (Exception ex)
            {
                logError(ex);

            }
        }

        private void loadPageTypeUrl()
        {
            var webApplication = WebApplicationFactory.GetInstance(WebApplicationId);
            var mappedPage = default(string);
            if (SelectedPageType.Equals(FILE_NOT_FOUND_404))
            {
                mappedPage = webApplication.FileNotFoundPage;
            }
            else
            {
                var key = (SPWebApplication.SPCustomPage)Enum.Parse(typeof(SPWebApplication.SPCustomPage), SelectedPageType);
                mappedPage = webApplication.GetMappedPage(key);
            }
            txtUrlValue.Text = mappedPage;
        }

        protected string WebApplicationId
        {
            get
            {
                return Request.QueryString["WebApplicationId"];
            }
        }

        protected string SelectedPageType
        {
            get
            {
                return ddlPageType.SelectedItem.Text;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(() =>
                {
                    var noError = true;
                    if (WebApplicationId != null)
                    {
                        var webApplication = WebApplicationFactory.GetInstance(WebApplicationId);
                        if (SelectedPageType.Equals(FILE_NOT_FOUND_404))
                        {
                            webApplication.FileNotFoundPage = txtUrlValue.Text;
                        }
                        else
                        {
                            var key = (SPWebApplication.SPCustomPage)Enum.Parse(typeof(SPWebApplication.SPCustomPage), SelectedPageType);
                            if (!webApplication.UpdateMappedPage(key, txtUrlValue.Text))
                            {
                                lblError.Text = "The provided value is not valid, please enter a valid relative url. i.e /_layouts/error.aspx";
                                noError = false;
                            }
                        }
                        webApplication.Update(true);
                    }
                    else
                    {
                        lblError.Text = "WebApplicationId should be passed to the page";
                        noError = false;
                    }

                    if (noError)
                    {
                        Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
                        Response.Flush();
                        Response.End();
                    }
                });

            }
            catch (Exception ex)
            {
                logError(ex);

            }

        }

        private void logError(Exception ex)
        {
            lblError.Text = "An erro occured " + ex.ToString();
        }
    }

    static class WebApplicationFactory
    {
        public static SPWebApplication GetInstance(string webAppGuid)
        {
            var guid = new Guid(webAppGuid);
            return SPFarm.Local.GetObject(guid) as SPWebApplication;
        }
    }

}
